﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mysoft.AppStartup.Application;
using Mysoft.Common.Extensions;
using Mysoft.Data.DBContext;

namespace Mysoft.AppStartup.Startup
{
    public static class ApplicationModeuleExtension
    {
        public static void UseModule(this WebApplication app) 
        {
            //启用跨域
            app.UseCors("any");
            //异常捕获
            app.UseMiddleware<HandlingMiddleware>();
            ((IApplicationBuilder)app).Use(HttpRequestMiddleware.Context);
            //jwt
            app.UseAuthentication();
            app.UseAuthorization();
            //配置HttpContext
            app.UseStaticHttpContext();
            app.MapControllers();
            //配置消息队列订阅事件
            app.UseSubscribe();

            if (app.Environment.IsDevelopment())
            {
                using (var serviceScope = ((IApplicationBuilder)app).ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
                {
                    serviceScope.ServiceProvider.GetService<EfDbContext>().Database.Migrate();
                    serviceScope.ServiceProvider.GetService<EfDbContext>().EnsureSeedData();
                }
            }
        }
    }
}
